package com.mbyte.easy.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mbyte.easy.admin.entity.*;
import com.mbyte.easy.admin.mapper.GroupMapper;
import com.mbyte.easy.admin.mapper.PptMapper;
import com.mbyte.easy.admin.mapper.VideoMapper;
import com.mbyte.easy.admin.service.*;
import com.mbyte.easy.common.constant.DraftLogConstant;
import com.mbyte.easy.common.constant.StatusConstant;
import com.mbyte.easy.common.constant.StatusPPTAudio;
import com.mbyte.easy.common.constant.StatusRecordVideo;
import com.mbyte.easy.common.controller.BaseController;
import com.mbyte.easy.common.web.AjaxResult;
import com.mbyte.easy.security.entity.SysUser;
import com.mbyte.easy.util.PageInfo;
import com.mbyte.easy.util.Utility;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
* <p>
* 前端控制器
* </p>
* @author lp
* @since 2019-03-11
*/
@Slf4j
@Controller
@RequestMapping("/admin/allot")
public class AllotController extends BaseController  {

    private String prefix = "admin/allot/";

    @Autowired
    private IAllotService allotService;

    @Autowired
    private IAudioService audioService;

    @Autowired
    private IPptService pptService;

    @Autowired
    private IGroupService groupService;
    @Autowired
    private IDraftService draftService;
    @Autowired
    private  IVideoService videoService;
    @Autowired
    VideoMapper videoMapper;
    @Autowired
    GroupMapper groupMapper;
    @Autowired
    PptMapper pptMapper;
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    /**
    * 查询列表
    *
    * @param model
    * @param pageNo
    * @param pageSize
    * @param allot
    * @return
    */
    @RequestMapping
    public String index(Model model,@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,@RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize, String createTimeSpace, String updateTimeSpace, Allot allot) {
        Page<Allot> page = new Page<Allot>(pageNo, pageSize);
        QueryWrapper<Allot> queryWrapper = new QueryWrapper<Allot>();
        if(!ObjectUtils.isEmpty(allot.getDraftId())) {
            queryWrapper = queryWrapper.like("draft_id",allot.getDraftId());
         }
        if(!ObjectUtils.isEmpty(allot.getAllotId())) {
            queryWrapper = queryWrapper.like("allot_id",allot.getAllotId());
         }
        if(!ObjectUtils.isEmpty(allot.getAllotnoId())) {
            queryWrapper = queryWrapper.like("allotNo_id",allot.getAllotnoId());
         }
        if(!ObjectUtils.isEmpty(allot.getStatusCode())) {
            queryWrapper = queryWrapper.like("status_code",allot.getStatusCode());
         }
        IPage<Allot> pageInfo = allotService.page(page, queryWrapper);
        model.addAttribute("searchInfo", allot);
        model.addAttribute("pageInfo", new PageInfo(pageInfo));
        return prefix+"list";
    }
    /**
    * 添加跳转页面
    * @return
    */
    @GetMapping("addBefore")
    public String addBefore(){
        return prefix+"add";
    }
    /**
    * 添加
    * @param allot
    * @return
    */
    @PostMapping("add")
    @ResponseBody
    public AjaxResult add(Allot allot){
        return toAjax(allotService.save(allot));
    }
    /**
    * 添加跳转页面
    * @return
    */
    @GetMapping("editBefore/{id}")
    public String editBefore(Model model,@PathVariable("id")Long id){
        model.addAttribute("allot",allotService.getById(id));
        return prefix+"edit";
    }
    /**
    * 添加
    * @param allot
    * @return
    */
    @PostMapping("edit")
    @ResponseBody
    public AjaxResult edit(Allot allot){
        return toAjax(allotService.updateById(allot));
    }
    /**
    * 删除
    * @param id
    * @return
    */
    @GetMapping("delete/{id}")
    @ResponseBody
    public AjaxResult delete(@PathVariable("id") Long id){
        return toAjax(allotService.removeById(id));
    }
    /**
    * 批量删除
    * @param ids
    * @return
    */
    @PostMapping("deleteAll")
    @ResponseBody
    public AjaxResult deleteAll(@RequestBody List<Long> ids){
        return toAjax(allotService.removeByIds(ids));
    }


    /**
     * @Author 张雪
     * @Description 音视频校对组长--批量分配PPT--视频校对人
     * @Date 2019/12/11 11:23
     * @Param
     * @return
     **/
    @RequestMapping("PptAllotAll")
    @ResponseBody
    public AjaxResult PptAllotAll(String idsBus,Model model,
                                  @RequestParam(value = "usernameList",required = false) String usernameList,String name){
//        Long currentUserid = allotService.selectUserIdByUsername(Utility.getCurrentUsername());
        String id=idsBus.substring(0,idsBus.length()-1);
        String[] idss=id.split(",");
        List<Long> draftid=new ArrayList<>(idss.length);
        for (int i = 0; i < idss.length; i++) {
            draftid.add(Long.parseLong(idss[i]));
        }
        SysUser sysUser = draftService.getUserIdByUserName(Utility.getCurrentUsername());
        //被分配人id
        SysUser sysUser1 = draftService.getUserIdByUserName(usernameList);
        String UUid=Utility.getUUID();
        for (int i = 0; i < draftid.size(); i++) {
            //更新稿件
            Ppt ppt=new Ppt();
            ppt.setId(draftid.get(i));
            ppt.setStatusCode(StatusRecordVideo.STATUS_PPT_AUDIO_AUVELEADER_SEND);
            ppt.setGroupId(UUid);
            ppt.setLastOperator(draftService.getUserIdByUserName(Utility.getCurrentUsername()).getId());
            pptService.updateById(ppt);
            //插入分配表
            Allot allot=new Allot();
            allot.setDraftId(draftid.get(i));
            allot.setAllotId(sysUser.getId());
            allot.setAllotnoId(sysUser1.getId());
            allot.setStatusCode(StatusRecordVideo.STATUS_PPT_AUDIO_AUVELEADER_SEND);
            allot.setCreateTime(LocalDateTime.now());
            allot.setUpdateTime(LocalDateTime.now());
            draftService.insertToAllot(allot);
            //插入group表

        }
        Group group=new Group();
        group.setGroupId(UUid);
        name = Utility.getGroupName(name);
        if(groupService.existGroupName(name)){
            return AjaxResult.error("组名【"+name+"】今日已存在！");
        }
        group.setName(name);
        group.setUserId(sysUser1.getId());
        draftService.insertToGroup(group);
//        Long downUserId = allotService.selectUserIdByUsername(usernameList);
//        log.info("========下属downUserId========="+downUserId);
//        String idsList[] = idsBus.split(",");
//        //String数组转成long型
//        log.info("=======idslist==========="+idsList);
//        Long[] arrayIds = new Long[idsList.length];
//        for (int i = 0; i <idsList.length ; i++) {
//            arrayIds[i] = Long.parseLong(idsList[i]);
//        }
//        List<Ppt> pptIds = new ArrayList<>();
//        log.info("==============arrayids==========="+arrayIds);
        //查询稿件id,得到ids实体List
//        Long[] draftIds = new Long[arrayIds.length];
//        for (int i = 0; i <arrayIds.length ; i++) {
//            Long draftIdById = pptService.selectDIdByID(arrayIds[i]);
//            draftIds[i] = draftIdById;
//            Ppt ppt = new Ppt();
//            ppt.setId(arrayIds[i]);
//            pptIds.add(ppt);
//        }
//        List<Allot> allotList = new ArrayList<>();
//        for (Long id:draftIds) {
//            //分配集合
//            allotList.add(new Allot().setDraftId(id).setAllotId(currentUserid).setAllotnoId(downUserId));
//        }
//
//        String uuid = Utility.getUUID();
//        Group group = new Group();
//        group.setGroupId(uuid).setUserId(downUserId);
//        groupService.save(group);
//
//        List pptList = new ArrayList();
//        for (Ppt id:pptIds) {
//            //更新PPT表
//            Ppt ppt = new Ppt();
//            ppt.setStatusCode(StatusRecordVideo.STATUS_PPT_AUDIO_AUVELEADER_SEND)//1017
//                .setGroupId(uuid).setId(id.getId());
//            pptList.add(ppt);
//        }
//        pptService.updateBatchById(pptList);
//        allotService.saveBatch(allotList);
        return toAjax(true);
    }
    /**
     * @Author 张雪
     * @Description 批量分配  音视频校对组长-->音频校对人
     * @Date 2019/12/11 11:23
     * @Param
     * @return
     **/
    @RequestMapping("AudioAllotAll")
    @ResponseBody
    public AjaxResult AudioAllotAll(String status, Model model, String ids,String name){
        name = Utility.getGroupName(name);
        if(groupService.existGroupName(name)){
            return AjaxResult.error("组名【"+name+"】今日已存在！");
        }
        String[] idss = ids.split(",");
        List<Long> audioid = new ArrayList<>(idss.length);
        for (int i = 0; i < idss.length; i++) {
            audioid.add(Long.parseLong(idss[i]));
        }
            SysUser sysUser = audioService.getUserIdByUserName(Utility.getCurrentUsername());
            SysUser sysUser1 = audioService.getUserIdByUserName(status);
            String UUid = Utility.getUUID();
            for (int i = 0; i < audioid.size(); i++) {
                Audio audio = new Audio();
                audio.setId(audioid.get(i));
                audio.setStatusCode(StatusRecordVideo.STATUS_PPT_AUDIO_AUVELEADER_SEND);//1017
                audio.setGroupId(UUid);
                audio.setLastOperator(audioService.getUserIdByUserName(Utility.getCurrentUsername()).getId());
                audioService.updateById(audio);

            Allot allot = new Allot();
            allot.setDraftId(audioService.getById(audioid.get(i)).getDraftId());
            allot.setAllotId(sysUser.getId());
            allot.setAllotnoId(sysUser1.getId());
            allot.setStatusCode(StatusRecordVideo.STATUS_PPT_AUDIO_AUVELEADER_SEND);//1017
            allot.setCreateTime(LocalDateTime.now());
            allot.setUpdateTime(LocalDateTime.now());
            audioService.insertToAllot(allot);

            applicationEventPublisher.publishEvent(new DraftLog().setActionType(DraftLogConstant.ACTION_ALLOT)
                    .setDraftId(audioService.getById(audioid.get(i)).getDraftId())
                    .setGroupId(UUid)
                    .setPrimaryState(StatusConstant.SUCCESS_FINAL)
                    .setAfterState(StatusRecordVideo.STATUS_PPT_AUDIO_AUVELEADER_SEND));
        }
        Group group = new Group();

        group.setName(name);
        group.setGroupId(UUid);

        group.setUserId(sysUser1.getId());
        audioService.insertToGroup(group);

//        log.info("分配下属--> {}",downUsername);
//        Long currentUserid = allotService.selectUserIdByUsername(Utility.getCurrentUsername());
//        Long downUserId = allotService.selectUserIdByUsername(downUsername);
//        String idsList[] = idsBus.split(",");
//        //String数组转成long型
//        Long[] arrayIds = new Long[idsList.length];
//        for (int i = 0; i <idsList.length ; i++) {
//            arrayIds[i] = Long.parseLong(idsList[i]);
//        }
//
//        List<Audio> audioIds = new ArrayList<>();
//        //查询稿件id,得到ids实体List
//        Long[] draftIds = new Long[arrayIds.length];
//        for (int i = 0; i <arrayIds.length ; i++) {
//            Long draftIdById = audioService.selectDraftIdById(arrayIds[i]);
//            draftIds[i] = draftIdById;
//            Audio audio = new Audio();
//            audio.setStatusCode(StatusRecordVideo.STATUS_PPT_AUDIO_AUVELEADER_SEND).setId(arrayIds[i]);
//            audioIds.add(audio);
//        }
//        List<Allot> allotList = new ArrayList<>();
//        String uuid = Utility.getUUID();
//        Group group = new Group();
//        for (Long draftId:draftIds) {
//            //分配集合
//            allotList.add(new Allot().setDraftId(draftId).setAllotId(currentUserid).setAllotnoId(downUserId));
//        }
//        group.setGroupId(uuid).setUserId(downUserId);
//        groupService.save(group);
//        allotService.saveBatch(allotList);
//        List<Audio> audioList = new ArrayList<>();
//        for (Audio id:audioIds) {
//            //更新音频表
//            Audio audio = new Audio();
//            audio.setStatusCode(StatusRecordVideo.STATUS_PPT_AUDIO_AUVELEADER_SEND)//1017
//                    .setGroupId(uuid).setId(id.getId());
//            audioList.add(audio);
//        }
//        log.info("uuid-->{}",uuid);
//        audioService.updateBatchById(audioList);
        return AjaxResult.success();
    }

    /**
     * @Author 张雪
     * @Description 批量分配  音频校对人-->音转视制作人
     * @Date 2019/12/11 11:23
     * @Param
     * @return
     **/
    @RequestMapping("AudioAllotAllToWorker")
    @ResponseBody
    public AjaxResult AudioAllotAllToWorker( String status, String ids){

        String id = ids.substring(0,ids.length() - 1);
        String[] idss = id.split(",");
        List<Long> audioid = new ArrayList<>(idss.length);
        log.info("=========================");
        for (int i = 0; i < idss.length; i++) {
            audioid.add(Long.parseLong(idss[i]));
        }
        String username = Utility.getCurrentUsername();
        SysUser sysUser = audioService.getUserIdByUserName(username);
        SysUser sysUser1 = audioService.getUserIdByUserName(status);
        for (int i = 0; i < audioid.size(); i++) {
            log.info("+++++++++++++++++++++++++");
            Audio audio = new Audio();
            audio.setId(audioid.get(i));
            audio.setStatusCode(StatusRecordVideo.STATUS_PPT_AUDIO_AUVEREADER_SEND);//1018
            audio.setLastOperator(audioService.getUserIdByUserName(Utility.getCurrentUsername()).getId());
            audioService.updateById(audio);

            Allot allot = new Allot();
            allot.setDraftId(audioService.getById(audioid.get(i)).getDraftId());
            allot.setStatusCode(StatusRecordVideo.STATUS_PPT_AUDIO_AUVEREADER_SEND);//1018
            allot.setAllotId(sysUser.getId());
            allot.setAllotnoId(sysUser1.getId());
            allot.setUpdateTime(LocalDateTime.now());
            allot.setCreateTime(LocalDateTime.now());
            audioService.insertToAllot(allot);
        }

//        String username = Utility.getCurrentUsername();
//        log.info("分配下属--> {}",downUsername);
//
//        Long currentUserid = allotService.selectUserIdByUsername(username);
//        Long downUserId = allotService.selectUserIdByUsername(downUsername);
//        String idsList[] = idsBus.split(",");
//        //String数组转成long型
//        Long[] arrayIds = new Long[idsList.length];
//        for (int i = 0; i <idsList.length ; i++) {
//            arrayIds[i] = Long.parseLong(idsList[i]);
//        }
//        List<Long> audioIdsList = Arrays.asList(arrayIds);
//        QueryWrapper<Audio> queryWrapper = new QueryWrapper<>();
//        queryWrapper.in("id",audioIdsList);
//        List<Audio> audio = audioService.list(queryWrapper);
//
//        List<Allot> allotList = new ArrayList<>();
//        List<Audio> audioList = audioService.list(queryWrapper);
//        for (int i = 0; i <audio.size() ; i++) {
//            //分配集合
//            allotList.add(new Allot().setDraftId(audio.get(i).getDraftId()).setAllotId(currentUserid).setAllotnoId(downUserId));
//            audioList.get(i).setStatusCode(StatusRecordVideo.STATUS_PPT_AUDIO_AUVEREADER_SEND)//1018
//                    .setId(audio.get(i).getId());
//
//
//    }
//        audioService.updateBatchById(audioList);
//        allotService.saveBatch(allotList);
        return toAjax(true);
    }
    /**
     * @Author  刘辉
     * @Description 批量分配  录屏对接人-->录屏制作人
     *     音视频校对组长---课程校对人
     * @Date 2019/02/13 11:23
     * @Param
     * @return
     **/
    @RequestMapping("PptAllotAllToWorker")
    @ResponseBody
    public AjaxResult PptAllotAllToWorker(String idsBus,Model model,
                                          String name,Long statusCode,String groupId){
        log.info("状态"+statusCode+"组"+groupId);
    if (statusCode == 1029) {
        //音视频校对组长分配
        String id = idsBus.substring(0, idsBus.length() - 1);
        String[] idss = id.split(",");
        List<Long> draftid = new ArrayList<>(idss.length);
        for (int i = 0; i < idss.length; i++) {
            draftid.add(Long.parseLong(idss[i]));
        }
        log.info("=====id================>{}", id);
        //分配人id
        String username = Utility.getCurrentUsername();
        SysUser sysUser = draftService.getUserIdByUserName(username);
        //被分配人id
        SysUser sysUser1 = draftService.getUserIdByUserName(name);
        log.info("===========被分配人姓名===========" + name);

        for (int i = 0; i < draftid.size(); i++) {
            //更新ppt表

            Video video = new Video();
            video.setDraftId(draftid.get(i));
            video.setStatusCode(StatusRecordVideo.STATUS_RECORD_AUVELEADER_DISTRIBUTION);//1037
            videoMapper.updateByDraftId(video);

            Group group = new Group();
            group.setGroupId(groupId);
            group.setUserId(sysUser1.getId());
            groupMapper.updateByGroupId(group);


            //插入分配表
            Allot allot = new Allot();
            allot.setDraftId(draftid.get(i));
            allot.setAllotId(sysUser.getId());
            allot.setAllotnoId(sysUser1.getId());
            allot.setStatusCode(StatusRecordVideo.STATUS_RECORD_AUVELEADER_DISTRIBUTION);
            allot.setCreateTime(LocalDateTime.now());
            allot.setUpdateTime(LocalDateTime.now());
            draftService.insertToAllot(allot);

             applicationEventPublisher.publishEvent(new DraftLog().setActionType(DraftLogConstant.ACTION_ALLOT)
                    .setDraftId(draftid.get(i))
                    .setGroupId(groupId)
                    .setPrimaryState(StatusRecordVideo.STATUS_RECORD_FUNCTIONARY_SUCCESS)
                    .setAfterState(StatusRecordVideo.STATUS_RECORD_AUVELEADER_DISTRIBUTION));

        }
    }else if (statusCode == 1034) {
        //录屏课程校对人分配
        String id = idsBus.substring(0, idsBus.length() - 1);
        String[] idss = id.split(",");
        List<Long> draftid = new ArrayList<>(idss.length);
        for (int i = 0; i < idss.length; i++) {
            draftid.add(Long.parseLong(idss[i]));
        }
        log.info("=====id================>{}", id);
        //分配人id
        String username = Utility.getCurrentUsername();
        SysUser sysUser = draftService.getUserIdByUserName(username);
        //被分配人id
        SysUser sysUser1 = draftService.getUserIdByUserName(name);
        log.info("===========被分配人姓名===========" + name);

        for (int i = 0; i < draftid.size(); i++) {
            //更新ppt表
            Ppt ppt=new Ppt();
            ppt.setDraftId(draftid.get(i));
            ppt.setUpdateTime(LocalDateTime.now());
            ppt.setStatusCode(StatusRecordVideo.STATUS_RECORD_BUTTJOJINT_DISTRIBUTION);
            pptMapper.updateStatusByDraftId(ppt);

            Group group = new Group();
            group.setGroupId(groupId);
            group.setUserId(sysUser1.getId());
            groupMapper.updateByGroupId(group);


            //插入分配表
            Allot allot = new Allot();
            allot.setDraftId(draftid.get(i));
            allot.setAllotId(sysUser.getId());
            allot.setAllotnoId(sysUser1.getId());
            allot.setStatusCode(StatusRecordVideo.STATUS_RECORD_BUTTJOJINT_DISTRIBUTION);//1036
            allot.setCreateTime(LocalDateTime.now());
            allot.setUpdateTime(LocalDateTime.now());
            draftService.insertToAllot(allot);

                 applicationEventPublisher.publishEvent(new DraftLog().setActionType(DraftLogConstant.ACTION_ALLOT)
                    .setDraftId(draftid.get(i))
                    .setGroupId(groupId)
                    .setPrimaryState(StatusPPTAudio.STATUS_PPT_FUNCTIONARY_SUCCESS)//1034
                    .setAfterState(StatusRecordVideo.STATUS_RECORD_BUTTJOJINT_DISTRIBUTION));
        }
    }
        return toAjax(true);
    }
}

